package com.utils;


import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * 连接数据库的工具类
 */
public class JDBCUtil {
    private static String url;
    private static String user;
    private static String password;

    // 注册驱动
    static {
        Properties pros = new Properties();
        try {
            pros.load(JDBCUtil.class.getClassLoader().getResourceAsStream("table_classwork.properties"));
            url = pros.getProperty("url");
            user = pros.getProperty("user");
            password = pros.getProperty("password");
            String driver = pros.getProperty("driver");
            Class.forName(driver);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 获取连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }

    // 释放资源
    public static void close(Connection conn, Statement st , ResultSet rs) {
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(st != null) {
            try {
                st.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
